// index.js

const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  data: {
    motto: '一键登录',
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    },
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
  },

  onLoad() {
    const cachedAvatar = wx.getStorageSync('avatarUrl')
    const cachedNickName = wx.getStorageSync('nickName')
    
    this.setData({
      userInfo: {
        avatarUrl: cachedAvatar || defaultAvatarUrl,
        nickName: cachedNickName || '',
      },
      // 移除默认头像判断
      hasUserInfo: !!cachedNickName && !!cachedAvatar
    })
  },

  bindViewTap() {
    if (!this.data.hasUserInfo) {
      wx.showToast({
        title: '请先填写头像和昵称',
        icon: 'none',
        duration: 2000
      })
      return
    }

    // 缓存最新用户信息
    wx.setStorageSync('avatarUrl', this.data.userInfo.avatarUrl)
    wx.setStorageSync('nickName', this.data.userInfo.nickName)

    wx.login({
      success: (res) => {
        if (!res.code) {
          wx.showToast({ title: '登录失败', icon: 'none' })
          return
        }

        wx.request({
          url: 'http://localhost:8080/login/' + res.code,
          method: 'POST',
          data: {
            avatarUrl: this.data.userInfo.avatarUrl,
            nickName: this.data.userInfo.nickName
          },
          success: (res) => {
            console.log(res)
            if (res.data.code !== 1) {
              wx.showToast({ title: res.data.msg || '登录失败', icon: 'none' })
              return
            }
            //使用 encodeURIComponent() 对参数进行编码,避免违法字符导致报错
            wx.navigateTo({
              url: `../chat/chat?avatarUrl=${encodeURIComponent(this.data.userInfo.avatarUrl)}&nickName=${encodeURIComponent(this.data.userInfo.nickName)}&token=${encodeURIComponent(res.data.data)}`
            })
          },
          fail: () => {
            wx.showToast({ title: '网络请求失败', icon: 'none' })
          }
        })
        console.log(res.code);
      },
      fail: () => {
        wx.showToast({ title: '登录失败', icon: 'none' })
      }
    })
  },

  onChooseAvatar(e) {
    const avatarUrl = e.detail.avatarUrl
    this.setData({
      'userInfo.avatarUrl': avatarUrl,
      // 仅检查昵称是否填写
      hasUserInfo: !!this.data.userInfo.nickName
    })
    wx.setStorageSync('avatarUrl', avatarUrl)
  },

  onInputChange(e) {
    const nickName = e.detail.value
    this.setData({
      'userInfo.nickName': nickName,
      // 仅检查昵称是否填写
      hasUserInfo: !!nickName
    })
    wx.setStorageSync('nickName', nickName)
  }
})